package com.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * 用于生成对pojo类中的字段国际化文件
 * 将传入类中的规定字段编入国际化文件中
 * @author Micahel
 */
public class PojoFieldTextHelper {
	private static String PROPERTIE_NAME = "message.properties";
	private static Properties p;
	private static InputStream input;
	
	/**
	 * 检查propertie需要修改的内容
	 * 必须配合使用 flushProperties
	 * @param c
	 */
	public static void checkProperties(Class c){
		try {
			if(input == null){
				input = ConfigHelper.getConfigStream(PROPERTIE_NAME);
				if(input != null){
					p = new Properties();
					p.load(input);
				}
			}
			if(p != null){
				String className = c.getSimpleName();
				char char1 = className.charAt(0);
				char newChar  = (char1+"").toLowerCase().charAt(0);
				className = className.replaceFirst(char1+"", newChar+"");//第一个字符改小写
				if(!p.containsKey(className)){
					p.setProperty(className,"");
					System.out.println("add "+className+" to properties");
				}
				Field[] f = c.getDeclaredFields();
				for (int i = 0; i < f.length; i++) {
					Class filedClass = f[i].getType();
					if(isBasicType(filedClass)){
						if(!p.containsKey(className+"."+f[i].getName())){
							p.setProperty(className+"."+f[i].getName(), "");
							System.out.println("add "+className+"."+f[i].getName()+" to properties");
						}
					}else{
						//System.out.println("skip pojo "+className+" filed "+f[i].getName()+" of type "+filedClass.getName());
					}
				}
			}else{
				System.out.println("config file "+PROPERTIE_NAME+" not found");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 必须要先使用checkProperties
	 */
	public static void flushProperties(){
		if(p != null){
			File oldFile = new File(".\\src\\"+PROPERTIE_NAME);
			if(oldFile.exists()){
				System.out.println("delete old file:"+oldFile.delete());
			}				
			File newFile = new File(".\\src\\"+PROPERTIE_NAME);
			FileOutputStream output;
			try {
				output = new FileOutputStream(newFile);
				p.store(output, "");
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public static boolean isBasicType(Class c){
		boolean result = false;
		String className = c.getName();
		if(c.isPrimitive()){
			result = true;
		}else if(className.contains("java.lang")){
			result = true;
		}else if(className.contains("java.sql")){
			result = true;
		}else if(className.contains(SysCache.getInstance().getSysConfig("pojo.base.class"))){
			result = true;
		}
		return result;
	}
	
}
